<?php
namespace app\api\controller;

use app\common\controller\Api;
use think\Db;

class Goods extends Api
{
    protected $noNeedLogin = '*';
    protected $noNeedRight = '*'; // 无需权限
    protected $noNeedCheck = '*'; // 关闭CSRF验证
    
    // 构造方法，添加跨域头信息并处理 OPTIONS 请求
    public function __construct()
    {
        parent::__construct();
        header('Access-Control-Allow-Origin: *'); // 允许所有来源的跨域请求
        header('Access-Control-Allow-Methods: *'); // 允许所有HTTP方法的跨域请求
        header('Access-Control-Allow-Headers: *'); // 允许所有的请求头
    }

    public function index()
    {
        var_dump(2222);die;
    }
    // 获取商品分类
    public function getcate()
    {
        $categories = Db::name('cate')->where('pid',0)->where('status','normal')->select();
    
        return json($categories);
    }

    // 获取商品分类下对应的商品
    public function getGoodsByCategory()
    {
        $categoryId = input('id');
        if($categoryId == 0){
            $goods = Db::name('product')
            ->where('status','on_sale')
            ->select();
        }else{
            $goods = Db::name('product')
            ->where('category_id', $categoryId)
            ->where('status','on_sale')
            ->select();
        }
        
        return json($goods);
    }
    
    // 获取商品详情
    public function getGoodsInfo()
    {
        $id = input('id');
        $goods = Db::name('product')
            ->where('id', $id)
            ->find();
        return json($goods);
    }
    
    //获取首页商品
    public function getHomeGoods()
    {
        $goods = Db::name('product')
            ->where('is_home', 1)
            ->where('status', 'on_sale')
            ->select();
        return json($goods);
    }

    // 提交订单
    public function submitOrder()
    {
        $data = $this->request->post([
            'name',
            'phone',
            'bank_card',
            'product_name',
            'sms_code'
        ]);

        // 生成随机订单号
        $data['order_number'] = date('YmdHis') . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT);

        // 这里可以添加数据验证逻辑

        $orderId = Db::name('order')->insertGetId($data);

        if ($orderId) {
            return json(['code' => 200, 'message' => '订单提交成功', 'order_id' => $orderId]);
        } else {
            return json(['code' => 500, 'message' => '订单提交失败']);
        }
    }
}